#!/usr/bin/python -O

import sys, os

from amqp import RoutingKey, Sender
from protomsg import ProtoMsg

# -- main start here --
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-i','--ip',  dest = 'ip',
      action='store', default = '127.0.0.1',
      help='ip address of the broker, default [%default]')
parser.add_option('-p','--port',  dest = 'port',
      action='store',   type = int,  default = 5672,
      help='port of the broker, default [%default]')
parser.add_option('--proto-src',  dest ='protoSrc',
      action='store', default = os.path.join(os.environ['HOME'], 'protos'),
      help='directory to store subscribe, default [%default]')
parser.add_option('-k','--routing-key',  dest ='routing_key',
      action='store', help='routing key')
parser.add_option('-m','--message',  dest ='message',
      action='store', help='message to send')

(opts, args) = parser.parse_args()

if not opts.routing_key:
    print 'Parameter error, routing key must be provieded'
    sys.exit(1)

rKey = RoutingKey(opts.routing_key)
mstring = ''
if opts.message:
    pMsg = ProtoMsg(opts.protoSrc, rKey.package, rKey.publication)

    pMsg.set_from_string(opts.message)

    if __debug__:
        print 'Sending\n{', pMsg, '}'

    mstring = pMsg.serialize_to_string()

    import socket
    try:
        sender = Sender(opts.ip, opts.port)
        sender.send(rKey, mstring)

    except socket.error, e:
        print e
        sys.exit(1)
